#include <QDebug>
#include "particle_system.h"

ParticleSystem::ParticleSystem(const int particleCount)
    :m_maxParticleCount(particleCount){

    m_particles = new float[particleCount * TOTAL_COMPONENT_COUNT];
}

ParticleSystem::~ParticleSystem() {
    delete[] m_particles;
}

void ParticleSystem::addParticle(const QVector3D &particle
                                 , const QVector3D &color
                                 , const QVector3D &direction
                                 , const float startTime) {

    int particleOffset = m_nextParticle * TOTAL_COMPONENT_COUNT;
    m_nextParticle++;

    if (m_nextParticle == m_maxParticleCount)
        m_nextParticle = 0;

    if (m_currentParticleCount < m_maxParticleCount)
        m_currentParticleCount++;

    int currOffset = particleOffset;
    m_particles[currOffset++] = particle.x();
    m_particles[currOffset++] = particle.y();
    m_particles[currOffset++] = particle.z();
    m_particles[currOffset++] = color.x();
    m_particles[currOffset++] = color.y();
    m_particles[currOffset++] = color.z();
    m_particles[currOffset++] = direction.x();
    m_particles[currOffset++] = direction.y();
    m_particles[currOffset++] = direction.z();
    m_particles[currOffset++] = startTime;
}

// for debug
void ParticleSystem::showParticles() {
    qDebug() << "============" << "particles count: " << m_currentParticleCount << "============";
    for (size_t i=0; i<m_currentParticleCount; i++) {
        size_t posIdx = i * TOTAL_COMPONENT_COUNT;
        qDebug() << "position:" << m_particles[posIdx] << ","
            << m_particles[posIdx + 1] << ","
            << m_particles[posIdx + 2];
        size_t colorIdx = posIdx + POSITION_COMPONENT_COUNT;
        qDebug() << "color:" << m_particles[colorIdx] << ","
            << m_particles[colorIdx + 1] << ","
            << m_particles[colorIdx + 2];
        size_t directionIdx = colorIdx + COLOR_COMPONENT_COUNT;
        qDebug() << "direction:" << m_particles[directionIdx] << ","
            << m_particles[directionIdx + 1] << ","
            << m_particles[directionIdx + 2];
        size_t startTimeIdx = directionIdx + DIRECTION_COMPONENT_COUNT;
        qDebug() << "start time:" << m_particles[startTimeIdx];
    }
}

QVector3D ParticleSystem::getParticlePosition(size_t idx) {
    assert(idx < m_currentParticleCount);
    size_t posIdx = idx * TOTAL_COMPONENT_COUNT; 
    QVector3D v{m_particles[posIdx], m_particles[posIdx+1], m_particles[posIdx+2]};
    return v;
}
